package com.sl.au.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Division;
import com.sl.au.entity.Point;
import com.sl.au.entity.GridAreaDetailInfo;
import com.sl.au.entity.GridAreaInfo;
import com.sl.au.entity.Option;
import com.sl.au.service.DeleteService;
import com.sl.au.service.DivisionService;
import com.sl.au.service.GridAreaInfoService;
import com.sl.au.service.OptionService;
import com.sl.au.service.IdentifyService;
import com.sl.au.service.impl.ListShowServiceImpl;
import com.sl.utils.MsgHelper;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@RestController
@RequestMapping("/ui/gridStreets")
public class GridAreaInfoStreetsController extends BaseController {
	@Autowired
	private GridAreaInfoService gridAreaInfoService;
	@Autowired
	private ListShowServiceImpl listShowServiceImpl;
	@Autowired
	private OptionService optionService;
	@Autowired
	private DivisionService divisionService;
	@Autowired
	private IdentifyService identifyService;
	@Autowired
	private DeleteService deleteService;

	@RequestMapping("/bindNode/{gridId}/{divisionId}")
	public MsgHelper bindNode(@PathVariable("gridId") String gridId, @PathVariable("divisionId") String divisionId) {
		GridAreaInfo gridAreaInfo = gridAreaInfoService.getRepository().findOne(gridId);
		Division division = divisionService.getRepository().findOne(divisionId);
		gridAreaInfo.setDivision(division);
		String gridIdentify = this.identifyService.getGirdIdentifyByAreaId("", gridAreaInfo.getDivision().getId());
		gridAreaInfo.setGridIdentify(gridIdentify);

		gridAreaInfoService.getRepository().save(gridAreaInfo);
		MsgHelper msgHelper = MsgHelper.success();
		msgHelper.setMsg("街巷区域绑定成功!");
		msgHelper.put("data", gridAreaInfo);
		return msgHelper;
	}

	@RequestMapping("/unbindNode/{id}")
	public MsgHelper unbindNode(@PathVariable("id") String id) {
		GridAreaInfo findOne = gridAreaInfoService.getRepository().findOne(id);
		findOne.setDivision(null);
		findOne.setGridIdentify(null);
		gridAreaInfoService.getRepository().save(findOne);
		MsgHelper msgHelper = MsgHelper.success();
		msgHelper.setMsg("街巷区域解绑成功!");
		msgHelper.put("data", findOne);
		return msgHelper;
	}

	@RequestMapping(value = "getAllNodes", method = RequestMethod.GET)
	public Map<String, Object> getAllNodes(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Division> node = null;
		node = divisionService.getAllNodes();
		List<Map<String, Object>> nodeMap = new ArrayList<Map<String, Object>>();

		nodeMap = divisionService.getNodeMap(node);

		map.put("code", 1);
		map.put("nodes", nodeMap);

		return map;
	}

	@RequestMapping("/initStateAndTpye")
	public MsgHelper initStateAndTpye() {
		List<Option> state = optionService.getRepository().findByGroup("启用状态");
		List<Option> type = optionService.getRepository().findByGroup("元素类型");
		return MsgHelper.success().put("state", state).put("type", type);
	}

	@RequestMapping(value = "/operateGrid", method = RequestMethod.POST)
	public MsgHelper save(@RequestBody Map<String, Object> map) {
		Object gai = map.get("gridAreaInfo");
		Object gad = map.get("gridAreaDetail");
		JSONObject gaiObj = JSONObject.fromObject(gai);
		GridAreaInfo gridAreaInfo = (GridAreaInfo) JSONObject.toBean(gaiObj, GridAreaInfo.class);

		GridAreaInfo temp = this.gridAreaInfoService.getRepository().findOne(gridAreaInfo.getId());
		String oldIdentify = "";
		if (temp != null) {
			oldIdentify = temp.getGridIdentify();
		}
		if(gridAreaInfo.getDivision()!=null){
			String gridIdentify = this.identifyService.getGirdIdentifyByAreaId(oldIdentify,
					gridAreaInfo.getDivision().getId());
			gridAreaInfo.setGridIdentify(gridIdentify);
		}

		List<GridAreaDetailInfo> detailInfos = null;
		if (gad != null) {
			detailInfos = new ArrayList<>();
			JSONArray array = JSONArray.fromObject(gad);
			for (int i = 0; i < array.size(); i++) {

				JSONObject gridDetailObj = array.getJSONObject(i);
				GridAreaDetailInfo gridAreaDetailInfo = (GridAreaDetailInfo) JSONObject.toBean(gridDetailObj,
						GridAreaDetailInfo.class);
				gridAreaDetailInfo.setGridInfo(gridAreaInfo);
				detailInfos.add(gridAreaDetailInfo);
			}
		}

		if (detailInfos != null && detailInfos.size() > 0) {
			gridAreaInfoService.saveSelfAndDetails(gridAreaInfo, detailInfos);
		} else {
			gridAreaInfoService.getRepository().save(gridAreaInfo);
		}
		MsgHelper helper =MsgHelper.success().put("attributes", gridAreaInfo);
		helper.setMsg("街巷信息保存成功！");
		return helper.put("gridDetails", detailInfos);
	}

	@RequestMapping(value = "/operateGrid/{id}", method = RequestMethod.DELETE)
	public Map<String, Object> deleteGridById(@PathVariable("id") String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		map = deleteService.deleteInfo(this.datasourceName ,GridAreaInfo.class ,id);
		if(map.get("code").equals(0)) {
			GridAreaInfo gridAreaInfo = gridAreaInfoService.getRepository().findOne(id);
			gridAreaInfoService.deleteSelfAndDetails(gridAreaInfo);
			map.put("msg", "删除街巷信息成功!");
		}
		
		return map;
	}

	@RequestMapping(value = "/getpage", method = RequestMethod.POST)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		String areaId = request.getParameter("tree");

		List<GridAreaInfo> areaInfos = null;
		Integer count = null;
		if (!StringUtils.hasText(areaId)||areaId.equals("0")) {
			/*if (StringUtils.hasText(key)) {

				areaInfos = gridAreaInfoService.getBindDivisionPageByKey(start, length, key, null, null);
			} else {
				areaInfos = gridAreaInfoService.getBindDivisionPage(start, length, null, null, null);
			}*/
		} else {
			areaInfos = gridAreaInfoService.getPageByArea("街巷",start, length,areaId, key, "createTime", null);
		}

		// List<GridAreaInfo> bindDivisionGridsNoPage=new ArrayList<>();
		if (!StringUtils.hasText(areaId)||areaId.equals("0")) {
			//count = gridAreaInfoService.getBindCount(key);// gridAreaInfoService.getCount(key);
		} else {
			count = gridAreaInfoService.getBindCountWithArea("街巷",areaId,key);
		}

		map.put("data", areaInfos);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	@RequestMapping(value = "/getBindingByArea", method = RequestMethod.GET)
	public Map<String, Object> getBindingByArea(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String areaId = request.getParameter("areaId");

		List<GridAreaInfo> areaInfos = this.gridAreaInfoService.getRepository().getBindByDivision(areaId,"街巷");
		map.put("data", areaInfos);
		map.put("code", 1);
		return map;
	}
	
	@RequestMapping(value = "/getWithOutArea", method = RequestMethod.GET)
	public Map<String, Object> getWithOutArea(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		List<GridAreaInfo> areaInfos = this.gridAreaInfoService.getRepository().getUnbindDivision("街巷");
		map.put("data", areaInfos);
		map.put("code", 1);
		return map;
	}

	@RequestMapping(value = "/getUnbindPage", method = RequestMethod.POST)
	public Map<String, Object> getUnbindPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		List<GridAreaInfo> areaInfos = null;
		Integer count = null;
		if (StringUtils.hasText(key)) {
			areaInfos = gridAreaInfoService.getUnbindDivisionPageByKey("街巷",start, length, key, null, null);
		} else {
			areaInfos = gridAreaInfoService.getUnbindDivisionPage("街巷",start, length, null, null, null);
		}

		// List<GridAreaInfo> bindDivisionGridsNoPage=new ArrayList<>();

		count = gridAreaInfoService.getUnbindCount(key,"街巷");// gridAreaInfoService.getCount(key);

		map.put("data", areaInfos);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping(method = RequestMethod.GET)
	private ModelAndView index(ModelAndView modelAndView) {
		List<Option> state = optionService.getRepository().findByGroup("启用状态");
		List<Option> type = optionService.getRepository().findByGroup("元素类型");
		List<Division> division = new ArrayList<>();// divisionService.getRepository().findAll();
		List<Division> parents = divisionService.getRepository().getParent();
		System.out.println("listShowHelper" + listShowServiceImpl);
		if (parents != null && parents.size() > 0) {
			division = listShowServiceImpl.getDivisionList("", new ArrayList<Division>(), parents);
		}
		modelAndView = createLayoutView("gridArea/streets");
		modelAndView.addObject("state", state);
		modelAndView.addObject("type", type);
		modelAndView.addObject("division", division);
		return modelAndView;
	}
	
	@RequestMapping(value = "/JudgePolygonOverlap", method = RequestMethod.POST)
	public MsgHelper JudgePolygonOverlap(@RequestBody Map<String, Object> map) {
		Object points = map.get("points");
		String gridId=(String)map.get("gridId");
		List<Point> detailInfos = null;
		if (points != null) {
			detailInfos = new ArrayList<>();
			JSONArray array = JSONArray.fromObject(points);
			for (int i = 0; i < array.size(); i++) {

				JSONObject pointObj = array.getJSONObject(i);
				Point point = (Point) JSONObject.toBean(pointObj,
						Point.class);
				detailInfos.add(point);
			}
		}
		Map<String, Object> gridmap=new HashMap<String,Object>();
		MsgHelper helper =MsgHelper.success().put("overlap", this.gridAreaInfoService.JudgePolygonOverlap(detailInfos,gridId,gridmap));
		helper.put("grid", gridmap.get("grid"));
		return helper;
	}
}
